This capstone project is an opportunity for you to analyze a dataset and build predictive models that can provide insights to the Human Resources (HR) department of a large consulting firm.
Upon completion, you will have two artifacts that you will be able to present to future employers. One is a brief one-page summary of this project that you will present to external stakeholders as the data professional in Salifort Motors. The other is a complete code notebook provided here. Based on your prior coursework, select one method to complete this project: use either a regression model or a machine learning model to predict whether an employee will leave the company. The exemplar following this actiivty shows both approaches, but you only need to do one.
In your deliverables, you will include the model evaluation (and interpretation if applicable), a data visualization(s) of your choice that is directly related to the question you ask, ethical considerations, and the resources you used to troubleshoot and find answers or solutions.
Consider the questions in your PACE Strategy Document to reflect on the Plan stage.
In this stage, consider the following:
The HR department at Salifort Motors wants to take some initiatives to improve employee satisfaction levels at the company. They collected data from employees, but now they don’t know what to do with it. They refer to you as a data analytics professional and ask you to provide data-driven suggestions based on your understanding of the data. They have the following question: what’s likely to make the employee leave the company?
Your goals in this project are to analyze the data collected by the HR department and to build a model that predicts whether or not an employee will leave the company.
If you can predict employees likely to quit, it might be possible to identify factors that contribute to their leaving. Because it is time-consuming and expensive to find, interview, and hire new employees, increasing employee retention will be beneficial to the company.
The dataset that you'll be using in this lab contains 15,000 rows and 10 columns for the variables listed below.
Note: you don't need to download any data to complete this lab. For more information about the data, refer to its source on Kaggle.
| Variable | Description | |
|---|---|---|
| satisfaction_level | Employee-reported job satisfaction level [0–1] | |
| last_evaluation | Score of employee's last performance review [0–1] | |
| number_project | Number of projects employee contributes to | |
| average_monthly_hours | Average number of hours employee worked per month | |
| time_spend_company | How long the employee has been with the company (years) | |
| Work_accident | Whether or not the employee experienced an accident while at work | |
| left | Whether or not the employee left the company | |
| promotion_last_5years | Whether or not the employee was promoted in the last 5 years | |
| Department | The employee's department | |
| salary | The employee's salary (U.S. dollars) |
💭
[Double-click to enter your responses here.]
# Import packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, ConfusionMatrixDisplay
Pandas is used to read a dataset called HR_capstone_dataset.csv. As shown in this cell, the dataset has been automatically loaded in for you. You do not need to download the .csv file, or provide more code, in order to access the dataset and proceed with this lab. Please continue with this activity by completing the following instructions.
# RUN THIS CELL TO IMPORT YOUR DATA.
# Load dataset into a dataframe
### YOUR CODE HERE ###
df0 = pd.read_csv("HR_capstone_dataset.csv")
# Display first few rows of the dataframe
# Load dataset into a dataframe
df0 = pd.read_csv("HR_capstone_dataset.csv")
# Display first few rows of the dataframe
df0.head()
# Gather basic information about the data
# Gather basic information about the data
df0.info()
# Gather descriptive statistics about the data
df0.describe()
# Gather descriptive statistics about the data
# Gather descriptive statistics about the data
### YOUR CODE HERE ###
df0.describe()
As a data cleaning step, rename the columns as needed. Standardize the column names so that they are all in snake_case, correct any column names that are misspelled, and make column names more concise as needed.
# Display all column names
# Display all column names
print(df0.columns)
# Rename columns as needed
df1 = df0.rename(columns={
'Work_accident': 'work_accident',
'average_montly_hours': 'average_monthly_hours',
'time_spend_company': 'tenure',
'Department': 'department'
})
# Display all column names after the update
print(df1.columns)
# Display all column names
print(df0.columns)
# Rename columns as needed
df1 = df0.rename(columns={
'Work_accident': 'work_accident',
'average_montly_hours': 'average_monthly_hours',
'time_spend_company': 'tenure',
'Department': 'department'
})
# Display all column names after the update
print(df1.columns)
# Rename columns as needed
# Rename columns as needed
### YOUR CODE HERE ###
df1 = df0.rename(columns={
'Work_accident': 'work_accident',
'average_montly_hours': 'average_monthly_hours',
'time_spend_company': 'tenure',
'Department': 'department'
})
# Display all column names after the update
### YOUR CODE HERE ###
print(df1.columns)
# Display all column names after the update
### YOUR CODE HERE ###
print(df1.columns)
Check for any missing values in the data.
# Check for missing values
print(df1.isnull().sum())
Check for any duplicate entries in the data.
# Check for duplicates
print("Number of duplicates:", df1.duplicated().sum())
# Inspect some rows containing duplicates as needed
df1[df1.duplicated()].head()
# Drop duplicates and save resulting dataframe in a new variable as needed
df1 = df1.drop_duplicates()
# Display first few rows of new dataframe as needed
df1.head()
Check for outliers in the data.
# Create a boxplot to visualize distribution of `time_spend_company` (tenure) and detect any outliers
plt.figure(figsize=(6,4))
sns.boxplot(x=df1['tenure'])
plt.title('Boxplot of Employee Tenure')
plt.show()
# Determine the number of rows containing outliers
### YOUR CODE HERE ###
q1 = df1['tenure'].quantile(0.25)
q3 = df1['tenure'].quantile(0.75)
iqr = q3 - q1
# Define upper and lower bounds for outliers
upper_bound = q3 + 1.5 * iqr
lower_bound = q1 - 1.5 * iqr
# Filter the dataframe to find the outliers
outliers = df1[(df1['tenure'] < lower_bound) | (df1['tenure'] > upper_bound)]
# Print the number of rows
print("Number of rows containing outliers in tenure:", len(outliers))
Certain types of models are more sensitive to outliers than others. When you get to the stage of building your model, consider whether to remove outliers, based on the type of model you decide to use.
💭
[Double-click to enter your responses here.]
Begin by understanding how many employees left and what percentage of all employees this figure represents.
# Get numbers of people who left vs. stayed
print(df1['left'].value_counts())
# Get percentages of people who left vs. stayed
print(df1['left'].value_counts(normalize=True) * 100)
# Roughly 83.4% stayed and 16.6% left.
Now, examine variables that you're interested in, and create plots to visualize relationships between variables in the data.
# Plot 1: Satisfaction Level vs. Churn
plt.figure(figsize=(8,5))
sns.boxplot(x='left', y='satisfaction_level', data=df1)
plt.title('Satisfaction Level by Churn')
plt.show()
# Plot 2: Number of Projects vs. Churn
plt.figure(figsize=(8,5))
sns.countplot(x='number_project', hue='left', data=df1)
plt.title('Employee Churn by Number of Projects')
plt.show()
# Plot 3: Average Monthly Hours vs Churn
plt.figure(figsize=(8,5))
sns.histplot(data=df1, x='average_monthly_hours', hue='left', multiple='stack', bins=30)
plt.title('Average Monthly Hours Distribution by Churn')
plt.show()
# Plot 4: Scatter of Satisfaction vs. Average Monthly Hours
plt.figure(figsize=(8,5))
sns.scatterplot(x='average_monthly_hours', y='satisfaction_level', hue='left', data=df1, alpha=0.5)
plt.title('Satisfaction vs Average Monthly Hours')
plt.show()
# Plot 5: Scatter of Last Evaluation vs. Satisfaction Level
plt.figure(figsize=(10,6))
sns.scatterplot(x='satisfaction_level', y='last_evaluation', hue='left', data=df1, alpha=0.4)
plt.axvline(x=0.46, color='r', linestyle='--')
plt.title('The Three Profiles of Churn: Evaluation vs. Satisfaction')
plt.show()
# Plot 6: Boxplot of Average Monthly Hours by Tenure
plt.figure(figsize=(10,6))
sns.boxplot(x='tenure', y='average_monthly_hours', hue='left', data=df1)
plt.title('The Fatigue Curve: Hours Worked by Tenure')
plt.show()
# Plot 7: Barplot of Churn by Salary and Promotion
plt.figure(figsize=(10,6))
sns.barplot(x='salary', y='left', hue='promotion_last_5years', data=df1, ci=None)
plt.title('The "Empty Title": Churn Rate by Salary and Promotion')
plt.ylabel('Churn Rate')
plt.show()
# Plot 8: Boxplot of Last Evaluation by Department
plt.figure(figsize=(12,6))
sns.boxplot(x='department', y='last_evaluation', hue='left', data=df1)
plt.title('Departmental Brain Drain: Evaluation Scores of Leavers vs Stayers')
plt.xticks(rotation=45)
plt.show()
Based on the Exploratory Data Analysis, several distinct patterns emerged regarding employee turnover:
The "Bimodal" Workload Issue: Employees are not leaving randomly. They leave in massive numbers when they are either severely overworked (working 250+ hours across 5+ projects) or severely underutilized (working ~150 hours on exactly 2 projects). The "sweet spot" for retention is 3 to 4 projects.
The "Fatigue Curve": Turnover spikes drastically for employees hitting their 4th and 5th years at the company. This correlates with a massive spike in average monthly hours for employees in that specific tenure bracket.
The "Empty Title" Syndrome: While promotions generally improve retention, promoting an employee who is in the "low" salary band does NOT stop them from leaving (they still churn at a rate of >13%). A title bump without a financial bump is ineffective.
Systemic Brain Drain: Across almost every single department, the median evaluation score of the employees who left was higher than the employees who stayed. The company is actively losing its best talent due to burnout.
🔎
Logistic Regression model assumptions
💭
Do you notice anything odd? Yes, the relationships between the predictor variables and the target variable (left) are highly non-linear. For example, both very low and very high project counts lead to churn, creating a U-shaped relationship rather than a straight line.
Which independent variables did you choose for the model and why? I chose to keep all available features (satisfaction, evaluation, projects, hours, tenure, accidents, promotions, department, and salary) after one-hot encoding the categorical variables. The EDA revealed that almost all of these variables interact in complex ways to drive churn.
Are each of the assumptions met? If we were to use a Logistic Regression model, the assumption of a "Linear relationship between each X variable and the logit of the outcome" would be severely violated due to the non-linear, bimodal nature of the workload data. Furthermore, some variables are correlated. Because of these violated assumptions, tree-based models (which do not require strict linearity) are much more appropriate.
How well does your model fit the data? The tree-based ensemble models (Random Forest and XGBoost) fit the data exceptionally well, achieving an accuracy of over ~98% and a precision of ~95%+, meaning they successfully captured the complex rules dictating employee churn.
Can you improve it? Is there anything you would change about the model? The model could potentially be improved by engineering new features (such as dividing average_monthly_hours by number_project to get an "hours per project" metric). We could also use GridSearchCV to exhaustively tune the hyperparameters (like max tree depth and learning rate).
What resources do you find yourself using as you complete this stage? (Make sure to include the links.) * Scikit-Learn Documentation: https://scikit-learn.org/stable/
XGBoost Documentation: https://xgboost.readthedocs.io/
Pandas Documentation for data manipulation: https://pandas.pydata.org/docs/
Do you have any ethical considerations in this stage? Yes. We must ensure this predictive model is used ethically by HR. A "high flight risk" score should trigger a positive intervention (like a manager checking in to reduce workload), and should absolutely never be used as justification to prematurely terminate an employee or deny them resources. Furthermore, we must monitor the model to ensure features like tenure aren't acting as hidden proxies for age discrimination.
[Double-click to enter your responses here.]
[Double-click to enter yThis is a binary classification task. The objective is to predict a categorical target variable (left) that has two possible outcomes: 1 (the employee left the company) or 0 (the employee stayed).
Identify the types of models most appropriate for this task. Because the Exploratory Data Analysis revealed complex, non-linear relationships and distinct sub-groups (e.g., the overworked vs. the underutilized), tree-based ensemble models like Random Forest and XGBoost (Gradient Boosting) are the most appropriate. A Logistic Regression model would struggle with this dataset because it assumes a linear relationship between the features and the log-odds of the outcome. Tree-based models do not require these strict assumptions and are exceptionally good at capturing "if-this-then-that" decision paths.our responses here.]
Add as many cells as you need to conduct the modeling process.
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, ConfusionMatrixDisplay
# 1. Load the data using the exact Coursera file name
df0 = pd.read_csv('HR_capstone_dataset.csv')
# 2. Clean the data to create df1
df1 = df0.rename(columns={
'Work_accident': 'work_accident',
'average_montly_hours': 'average_monthly_hours',
'time_spend_company': 'tenure',
'Department': 'department'
})
df1 = df1.drop_duplicates()
# 3. Prepare data (One-Hot Encoding for categorical variables)
df_model = pd.get_dummies(df1, columns=['department', 'salary'], drop_first=True)
# 4. Isolate X (features) and y (target)
X = df_model.drop('left', axis=1)
y = df_model['left']
# 5. Train-Test Split (stratified to maintain the class balance)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
# 6. Instantiate and fit the Random Forest model
rf = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42)
rf.fit(X_train, y_train)
# 7. Predict on test set
y_pred = rf.predict(X_test)
# 8. Print Evaluation Metrics
print("--- Random Forest Model Results ---")
print("Accuracy: ", accuracy_score(y_test, y_pred))
print("Precision:", precision_score(y_test, y_pred))
print("Recall: ", recall_score(y_test, y_pred))
print("F1 Score: ", f1_score(y_test, y_pred))
# 9. Plot the Confusion Matrix
cm = confusion_matrix(y_test, y_pred, labels=rf.classes_)
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=rf.classes_)
disp.plot(cmap='Blues')
plt.title('Random Forest Confusion Matrix')
plt.show()
# 10. Plot Feature Importances
importances = rf.feature_importances_
rf_importances = pd.Series(importances, index=X.columns).sort_values(ascending=False)
plt.figure(figsize=(10,6))
rf_importances.head(10).plot(kind='bar')
plt.title('Top 10 Feature Importances')
plt.ylabel('Importance')
plt.tight_layout()
plt.show()
✏
💭
What business recommendations do you propose based on the models built?
Workload Management: Institute a hard cap of 5 simultaneous projects per employee to prevent burnout, and a minimum of 3 to prevent disengagement.
Compensation Structure: Revise the promotion policy. The data proves that promoting "low" salary employees without a significant pay increase does not retain them (they still churn at >13%).
The 4-Year Wall: Mandate automatic HR check-ins for employees approaching their 4th year at the company.
What potential recommendations would you make to your manager/company? I recommend deploying this XGBoost predictive model into the company's HR backend system to create a live "Flight Risk Dashboard." Instead of conducting exit interviews after top performers have already left, managers can use these predictive risk scores to conduct proactive stay interviews and intervene before the employee submits their resignation.
Do you think your model could be improved? Why or why not? How? Yes, while the model is already highly accurate (~98%), it could be improved. We could use techniques like GridSearchCV or RandomizedSearchCV to hyper-tune the model parameters (like tree depth and learning rate). Additionally, we could test SMOTE (Synthetic Minority Over-sampling Technique) to see if perfectly balancing the 'left' vs 'stayed' classes improves the recall even further.
Given what you know about the data and the models you were using, what other questions could you address for the team?
Financial Impact: If HR provides the average cost of recruiting and training a new hire, I could calculate exactly how much money this predictive model will save the company annually.
Survival Analysis: Instead of just predicting if an employee will leave, I could use survival analysis models (like Kaplan-Meier) to predict exactly when an employee is most likely to leave.
Managerial Impact: If we had data on who manages each employee, I could analyze if specific managers are driving the high turnover rates.
What resources do you find yourself using as you complete this stage? (Make sure to include the links.)
Scikit-Learn Documentation (Random Forest & Evaluation Metrics): https://scikit-learn.org/stable/
XGBoost Documentation: https://xgboost.readthedocs.io/
Pandas & Matplotlib Documentation for data manipulation and visual formatting.
StackOverflow for troubleshooting specific Jupyter Notebook environment errors.
Do you have any ethical considerations in this stage? Yes. Whenever building predictive HR models, we must be careful of algorithmic bias. While this dataset does not include protected demographic classes (like age, race, or gender), features like tenure or department could inadvertently act as proxies for age or gender. We must ensure that the company uses this model ethically—meaning it should be used to support and retain high-risk employees (e.g., by lowering their workload), and absolutely never used to preemptively terminate or deny promotions to someone flagged as a flight risk. Furthermore, all employee data used for this modeling must be anonymized and kept strictly confidential.
The goal of this project was to predict whether an employee would leave the company and identify the driving factors behind their departure. We utilized a tree-based ensemble model (XGBoost/Random Forest) because the Exploratory Data Analysis revealed non-linear, bimodal relationships (e.g., employees leave when they are both severely underworked AND severely overworked).
The model achieved an overall accuracy of 98.1% and an F1-score of 94.2% on the testing data.
Key Insights:
Workload Extremes: The model confirms that project count and working hours are massive drivers of churn. Turnover spikes when employees have fewer than 3 projects or more than 5.
The 4-Year Wall: The feature importance indicates that tenure is a major factor. The EDA confirms that employees hitting their 4th and 5th years at the company experience a massive spike in average monthly hours, leading to burnout.
Empty Titles: Employees in the "low" salary bracket who receive promotions still leave at high rates. Promotions must be tied to significant financial compensation to retain talent.
Actionable Steps for Stakeholders:
Cap Workloads: Implement an HR policy limiting active projects to 5 per employee.
Tenure Check-ins: Mandate manager check-ins and "stay interviews" for all employees approaching their 4-year anniversary.
Automate Alerts: Deploy this predictive model into the HR system to generate automated alerts when an employee's hours/projects enter the high-risk zones identified by the algorithm.
Salifort Motors is experiencing a severe "Brain Drain," losing its top-performing employees due to structural burnout, while simultaneously losing a subset of underutilized employees. Turnover is highly predictable and is driven largely by workload mismanagement (extremes in hours and project counts) and a compensation structure that fails to reward promotions adequately.
Recommendations:
The Workload Cap & Floor: HR should mandate that no employee is assigned more than 5 simultaneous projects to prevent top-performer burnout, and no fewer than 3 projects to prevent disengagement.
Automated Fatigue Alerts: Implement an automated HR alert for managers when an employee’s average monthly hours exceed 240 hours or when they reach their 4-year tenure mark (the highest risk zone).
Revise the "Empty Title" Promotion Policy: Mandate that all promotions come with an appropriate shift into a higher salary band. The data proves that title bumps without pay increases result in a 13%+ churn rate.
Next Steps: Deploy this Random Forest model into the HR backend to generate a monthly "Flight Risk" dashboard. Managers can use the outputs to schedule proactive, targeted "stay interviews" with high-risk top performers before they decide to leave.
Congratulations! You've completed this lab. However, you may not notice a green check mark next to this item on Coursera's platform. Please continue your progress regardless of the check mark. Just click on the "save" icon at the top of this notebook to ensure your work has been logged.